# 加载系统库
from django.http import JsonResponse
from django import forms
from django.forms.models import model_to_dict

# 加载数据库
from web.models import Users, RealNameIdentity

# 加载自定义工具库
from web import Tools

# 定义FormsModel, 用在用户注册时的校验
class FormsModel(forms.ModelForm):
    class Meta:
        model = Users
        fields = "__all__"

# 自定义 model_to_dict
def filter_model_to_dict(data, template=0):
    new_data = model_to_dict(data)


    if template == 0:
        # 用户
        new_data["user_avatar_img"] = data.user_avatar_img.url

        # 关闭密码
        del new_data["password"]
    elif template == 1:
        new_data["create_time"] = data.create_time.strftime("%Y-%m-%d")
        # 身份证
        new_data["id_card_front_image"] = data.id_card_front_image.url
        new_data["id_card_back_image"] = data.id_card_back_image.url
        new_data["user_info"] = {
            "user_number": data.user.user_number,
            "name": data.user.name,
            "phone": data.user.phone,
            "user_is_authenticated": data.user.user_is_authenticated,
        }





    return new_data


# API: 用户注册
def register(request):
    if request.method == 'POST':
        info = FormsModel(request.POST)
        if info.is_valid():
            info.save()
            # 校验成功

            return JsonResponse(Tools.ReturnData(msg="注册成功", data=filter_model_to_dict(info.instance)))

        err_info = Tools.Forms_GetError(info)
        return JsonResponse(Tools.ReturnData(
            code=400,
            msg=err_info[1],
            data=err_info[0],
            template=0
        ))
    return JsonResponse(Tools.ReturnData(template=1))

# api:登录
def login(request):
    if request.method == 'POST':
        phone = request.POST.get("phone")
        password = request.POST.get("password")
        user_info = Users.objects.filter(phone=phone, password=password).first()
        if user_info:
            user_info = filter_model_to_dict(user_info)
            return JsonResponse(Tools.ReturnData(
                msg="登录成功",
                data=user_info
            ))
        else:

            # 判断有没有这个用户
            if Users.objects.filter(phone=phone).first():
                return JsonResponse(Tools.ReturnData(
                    msg="密码错误",
                    data=None,
                    code=400
                ))




            return JsonResponse(Tools.ReturnData(
                msg="请前往注册",
                data=None,
                code=400
            ))
    return JsonResponse(Tools.ReturnData(template=1))

# api: 实名认证
# 表单
class smrz_forms(forms.ModelForm):
    class Meta:
        model = RealNameIdentity
        fields = "__all__"
def smrz(request):
    if request.method == 'POST':
        info = smrz_forms(request.POST, request.FILES)
        if info.is_valid():
            info.save()
            return JsonResponse(Tools.ReturnData(
                msg="提交成功,等待审核",
                data= filter_model_to_dict(info.instance,template=1)
            ))
        err_info = Tools.Forms_GetError(info)
        return JsonResponse(Tools.ReturnData(code=400, msg="您已提交过实名认证",data=err_info[0]))
    elif request.method == 'GET':
        user_id = request.GET.get("user_id")
        if user_id:
            user_info = RealNameIdentity.objects.filter(user_id=user_id).first()
            if user_info:
                return JsonResponse(Tools.ReturnData(data=filter_model_to_dict(user_info, template=1),
                                                     msg=f"获取{user_info.name}实名信息成功"))
            return JsonResponse(Tools.ReturnData(code=400, msg=f"未找到您的实名信息"))
        return JsonResponse(Tools.ReturnData(code=400, msg="未提供用户id"))
    return JsonResponse(Tools.ReturnData(template=1))

# 获取我的额度
def get_user_quota(request):
    if request.method == 'GET':
        user_id = request.GET.get("user_id")
        if user_id:
            user_info = Users.objects.filter(id=user_id).first()
            if user_info:
                return JsonResponse(Tools.ReturnData(data=filter_model_to_dict(user_info),
                                                     msg=f"获取{user_info.name}额度成功"))
            return JsonResponse(Tools.ReturnData(code=400, msg=f"未找到您的额度"))
        return JsonResponse(Tools.ReturnData(code=400, msg="未提供用户id"))
    return JsonResponse(Tools.ReturnData(template=1))



# 审核实名认证
def auth_list(request):
    if request.method == 'GET':
        user_id = request.GET.get("user_id")
        status = request.GET.get("status", 1)
        if user_id:
            data = RealNameIdentity.objects.filter(id=user_id).first()
            if data:
                user_info = Users.objects.filter(id=data.user.id).first()
                if user_info.user_is_authenticated == 0:
                    if int(status) == 1:
                        user_info.user_is_authenticated = 1
                    else:
                        user_info.user_is_authenticated = 2
                    user_info.save()
                else:
                    return JsonResponse(Tools.ReturnData(code=400, msg="已审核过, 不可再次修改"))
                data.is_audit = True
                data.save()
                return JsonResponse(Tools.ReturnData(data=filter_model_to_dict(data, template=1),
                                                     msg=f"已修改{data.name}实名认证状态"))
            return JsonResponse(Tools.ReturnData(code=400, msg="未找到实名认证信息"))
        return JsonResponse(Tools.ReturnData(code=400, msg="未提供用户id"))
    return JsonResponse(Tools.ReturnData(template=1))

# 获取需要实名认证的列表
def get_in_auth_list(request):
    if request.method == 'GET':
        status = request.GET.get("status")
        if status:
            a = []
            for i in Users.objects.filter(user_is_authenticated=status):
                a.append(RealNameIdentity.objects.filter(user_id=i.id).first())
            return JsonResponse(Tools.ReturnData(data=[filter_model_to_dict(i, template=1) for i in a]))
        else:
            data = RealNameIdentity.objects.all()
            return JsonResponse(Tools.ReturnData(data=[filter_model_to_dict(i, template=1) for i in data]))
    return JsonResponse(Tools.ReturnData(template=1))


# 修改手机号、密码
def change_phone_password(request):
    if request.method == 'POST':
        status = request.POST.get("status") # 1:修改密码 2:修改手机号
        user_id = request.POST.get("user_id")
        if status == "1":
            password = request.POST.get("password")
            newpassword = request.POST.get("newpassword")
            if password:
                user_info = Users.objects.filter(id=user_id).first()
                if user_info:
                    if user_info.password == password:
                        user_info.password = newpassword
                        user_info.save()
                        return JsonResponse(Tools.ReturnData(msg="修改密码成功"))
                    return JsonResponse(Tools.ReturnData(code=400, msg="原密码错误"))
                return JsonResponse(Tools.ReturnData(code=400, msg="未找到用户"))
            return JsonResponse(Tools.ReturnData(code=400, msg="请输入密码"))
        elif status == "2":
            phone = request.POST.get("phone")
            if phone:
                user_info = Users.objects.filter(id=user_id).first()
                if user_info:
                    user_info.phone = phone
                    user_info.save()
                    return JsonResponse(Tools.ReturnData(msg="修改手机号成功"))
                return JsonResponse(Tools.ReturnData(code=400, msg="未找到用户"))
            return JsonResponse(Tools.ReturnData(code=400, msg="请输入手机号"))
        return JsonResponse(Tools.ReturnData(code=400, msg="请选择修改类型"))

    return JsonResponse(Tools.ReturnData(template=1))